package com.core.system.reckerMQ.imMessage;

import com.alibaba.fastjson.JSONObject;
import com.core.system.dao.ImMessageRecordMapper;
import com.pojo.entity.ImMessageRecordEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;

/**
 * 存储聊天记录
 */
@Component
@Slf4j
public class ImServerMessageRecord implements ImServer{

    private ImMessageRecordMapper imMessageRecordMapper;


    public ImServerMessageRecord(ImMessageRecordMapper imMessageRecordMapper){
        this.imMessageRecordMapper = imMessageRecordMapper;
    }

    @Override
    public void execute(ImServerInfo info) {
        log.info("执行聊天记录存储方法，获取body:{}",info.getBody());
        MessageInfo messageInfo = JSONObject.parseObject(info.getBody(), MessageInfo.class);
        ImMessageRecordEntity imMessageRecordEntity = new ImMessageRecordEntity();
        BeanUtils.copyProperties(messageInfo,imMessageRecordEntity);
        imMessageRecordEntity.setRecipientId(Long.parseLong(messageInfo.getRecipientId()));
        imMessageRecordEntity.setRequestId(Long.parseLong(messageInfo.getRequestId()));
        if (StringUtils.isNotBlank(messageInfo.getRequestDate())) {
            Instant instant = Instant.ofEpochMilli(Long.parseLong(messageInfo.getRequestDate()));
            ZoneId zone = ZoneId.systemDefault();
            imMessageRecordEntity.setRequestDate(LocalDateTime.ofInstant(instant, zone));
        }
        String chatIdentifier = Base64.getEncoder().encodeToString((messageInfo.getRequestId()+messageInfo.getRecipientId()).getBytes());
        imMessageRecordEntity.setChatIdentifier(chatIdentifier);
        imMessageRecordMapper.insert(imMessageRecordEntity);
    }
}
